package com.boot.interceptor;

import com.boot.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Chunsheng.Zhang
 * @date 2021/4/8 11:22
 * @description : TODO
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验用户请求的url是否在用户的权限范围内

        //1 取出用户的身份信息
        UserDto userDto = (UserDto)request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if(userDto == null){//用户未登录
            writeContent(response,"用户未登录");
        }

        //请求的url
        String uri = request.getRequestURI();
        if(userDto.getAuthorities().contains("m1")&&uri.contains("/user/m1")||
                userDto.getAuthorities().contains("m2")&&uri.contains("/user/m2")){
            return true;
        }

        writeContent(response,"没有权限，拒绝访问！");
        return false;
    }



    private void writeContent(HttpServletResponse response,String msg) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(msg);
        writer.close();
        response.resetBuffer();//清缓存
    }
}
